<template>
  <Layout style="height: 100%" class="main">
    <Sider hide-trigger collapsible :width="220" :collapsed-width="50" v-model="collapsed" class="left-sider" :style="{overflow: 'hidden'}">
      <side-menu accordion ref="sideMenu" :active-name="activeName" :collapsed="collapsed" @on-select="turnToPage" :menu-list="menuList" class="sider-menu">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div :class="['sider-user-info', 'sider-user-info-xa', collapsed ? 'sider-user-info-short' : null]">
          <div :style="{ 'text-align': 'center', display: collapsed ? 'none' : 'block', overflow: 'hidden', height: '110px' }">
            <img src="@/assets/images/bin-xa-logo-2.png" alt="logo">
            <p style="color: white;font-size: 18px;font-weight: bold;">物联网采集云平台</p>
          </div>
        </div>
      </side-menu>
    </Sider>

    <Layout>
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :userName="userDetail.userName" :user-avatar="userAvatar" :user-level="userDetail.userLv"/>
          <!-- <language v-if="$config.useI18n" @on-lang-change="setLocal" style="margin-right: 10px;" :lang="local"/> -->
          <!-- <span class="sys-logout">
            <Button type="text" class="logout-btn" @click="whetherLogout"><Icon :size="20" type="md-log-out" style="vertical-align: sub;"/>注销</Button>
          </span> -->
          <warn-info :count="warnCounts"></warn-info>
          <email-info v-show="env === 'development'"></email-info>
          <error-store v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader && env === 'development'" :has-read="hasReadErrorPage" :count="errorCount"></error-store>
          <page-settings v-show="env === 'development'" style="margin-right: 10px;"></page-settings>
          <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/>
        </header-bar>
      </Header>

      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/>
          </div>
          <Content class="content-wrapper">
            <!-- <transition-group name="slide-right-fade-reverse" mode="out-in"> -->
            <!-- 首页 内部页面 -->
            <!-- <home v-show="currentTabs === 'home'" :key="'home'"></home> -->
            <!-- <keep-alive :include="cacheList">
              <router-view/>
            </keep-alive> -->
            <!-- <component
              v-for="item in hasOpenComponentsArr"
              :key="item.name"
              :is="item.name"
              v-show="$route.path === item.meta.realPath">
            </component> -->
            <iframe-view
              ref="iframe-view"
              class="iframe-view"
              v-for="item in hasOpenComponentsArr"
              :key="item.name"
              :src="item.meta.url"
              :name="item.name"
              :finish.sync="item.meta.finish"
              v-show="currentTabs === item.name">
            </iframe-view>
            <!-- </transition-group> -->
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
          </Content>
        </Layout>
      </Content>

      <div class="footer-con">
        <div class="footer-left">Copyright © {{curYear}}</div>
        <div class="footer-right"><strong>Version</strong><span>: {{$config.version}}</span></div>
      </div>
    </Layout>

    <Modal v-model="logoutModal" width="360" class="logout-modal">
      <p slot="header" style="color: #f60;">
        <Icon type="ios-information-circle"></Icon>
        <span>系统信息</span>
      </p>
      <div style="text-align:center; font-size: 16px;">
        <p>您确定要退出系统吗？</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="logoutLoading" @click="logout">退出</Button>
      </div>
    </Modal>

    <!-- 实时报警弹窗 -->
    <!-- <warn-realtime-modal :toggle.sync="ifOpenWarnModal"></warn-realtime-modal> -->

    <!-- 个人信息弹窗 -->
    <user-info-form :toggle.sync="showMyselfModal"></user-info-form>

    <!-- token弹窗 -->
    <!-- <token-modal :toggle.sync="!$store.state.user.hasToken"></token-modal> -->
  </Layout>
</template>

<script>
// import SideMenu from './components/side-menu'
// import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
// import Language from './components/language'
import ErrorStore from './components/error-store'
import EmailInfo from './components/email-info'
import WarnInfo from './components/warn-info'
import PageSettings from './components/page-settings'
// import WarnRealtimeModal from './components/warn-realtime-modal'
import UserInfoForm from './components/user/user-info-form'
import TokenModal from './components/user/token-modal'
import { mapMutations, mapActions, mapGetters } from 'vuex'
// import { getNewTagList, routeEqual } from '@/libs/util'
// import { routeEqual } from '@/libs/util'
// import routers from '@/router/routers'
// import Main from '@/components/main'
import config from '@/config'
// import { systemMenuV2 } from '@/api/menu'
// import { filterTree } from '@/libs/util'
// import IframeView from './iframe-view'
import IframeView from '@/components/iframe-view'
import './main.less'
import { iotsysWarnList } from '@/api/warn'
import { userJAELogin } from '@/api/account/user'
import avatarImg from '@/assets/images/avatar-img.png'
// import { filterTime } from '@/libs/util'
const SideMenu = () => import('./components/side-menu') // 改变父组件、子组件生命周期循环顺序
const HeaderBar = () => import('./components/header-bar')
let iframeRoutes = []
let iframeNames = []
export default {
  name: 'Main',
  provide () {
    return {
      openWarnModal: this.openWarnModal
    }
  },
  components: {
    SideMenu,
    HeaderBar,
    // Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    EmailInfo,
    WarnInfo,
    PageSettings,
    // WarnRealtimeModal,
    UserInfoForm,
    TokenModal,
    // Main,
    IframeView
  },
  data () {
    return {
      avatarImg,
      env: process.env.NODE_ENV,
      value1: false,
      collapsed: false,
      isFullscreen: false,
      userLv: '-',
      userName: '-',
      accountInfo: {
        name: '-',
        level: 1,
        avatar: ''
      },
      userDetail: {
        userLv: '-',
        userName: '-'
      },
      logoutModal: false,
      logoutLoading: false,
      sysForm: {
        night: false
        // tabs: true
      },
      ifOpenWarnModal: false,
      warnCounts: 0,
      curYear: this.$store.state.app.currentYear,
      showMyselfModal: false,
      wss: null,
      showTokenModal: false,
      nav: [],
      menuTree: [],
      findHome: 0,
      timer: null
      // currentTabs: 'home'
    }
  },
  computed: {
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvatar () {
      return avatarImg
    },
    cacheList () {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    menuList () {
      return this.menuTree
    },
    activeName () {
      return this.$store.state.user.currentTabs
    },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    },
    currentTabs () {
      return this.$store.state.user.currentTabs
    },
    hasOpenComponentsArr () {
      let arr = [...this.$store.state.user.iframeRoutes]
      return arr.filter(item => item.ifRender)
    }
  },
  watch: {
    '$route' (newRoute) {
    }
  },
  async created () {
    // demo测试
    this.userLv = 3
    this.userName = '管理员'
    this.userDetail = {
      userLv: 3,
      userName: '管理员'
    }
    // this.accountInfo = res.data.data
    sessionStorage.setItem('username', '管理员')
    // sessionStorage.setItem('userInfo', JSON.stringify(res.data.data))
    let demo = [
      {
        description: '功能导航',
        icon: 'ios-apps',
        id: '100',
        isOutSide: '0',
        name: 'plugins',
        parentId: 'root',
        path: 'Main',
        showLevel: '2',
        sort: '0',
        title: '功能导航',
        url: '',
        uuid: 'd948faa3364543febcd76ef4f53876b3',
        children: [
          {
            description: '功能导航 - 数据概览',
            icon: 'md-podium',
            id: '101',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '数据概览',
            url: 'https://cn.vuejs.org/v2/guide/index.html',
            uuid: '3ad143340e434bbebf3246d689f902fe',
            children: []
          }
        ]
      },
      {
        description: '检测管理',
        icon: 'ios-speedometer',
        id: '200',
        isOutSide: '0',
        name: 'plugins',
        parentId: 'root',
        path: 'Main',
        showLevel: '2',
        sort: '0',
        title: '检测管理',
        url: '',
        uuid: '8bca30c5728e49809d7e979597750993',
        children: [
          {
            description: '检测管理 - 视频接入',
            icon: 'ios-videocam',
            id: '201',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '视频接入',
            url: 'https://ant.design/index-cn',
            uuid: '4405f17577d44532964fe3955acf3352',
            children: []
          },
          {
            description: '检测管理 - 视频识别',
            icon: 'ios-film',
            id: '202',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '1',
            title: '视频识别',
            url: 'https://hs.blizzard.cn/',
            uuid: '3728e161500d45c0a1be5761eacb015f',
            children: []
          }
        ]
      },
      {
        description: '告警管理',
        icon: 'md-warning',
        id: '300',
        isOutSide: '0',
        name: 'plugins',
        parentId: 'root',
        path: 'Main',
        showLevel: '2',
        sort: '0',
        title: '告警管理',
        url: '',
        uuid: '8e6b183b6c614bd2848dc7c5c4f65e8b',
        children: [
          {
            description: '告警管理 - 告警处置',
            icon: 'md-options',
            id: '302',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '告警处置',
            url: 'https://ant.design/index-cn',
            uuid: 'a04f8bbada2b45ce8cc8ddd1826bf20b',
            children: []
          },
          {
            description: '告警管理 - 告警推送',
            icon: 'md-list-box',
            id: '302',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '告警推送',
            url: 'https://ant.design/index-cn',
            uuid: 'eb2eeeb576f2424595016f1b95eba195',
            children: []
          }
        ]
      },
      {
        description: '系统设置',
        icon: 'md-settings',
        id: '400',
        isOutSide: '0',
        name: 'plugins',
        parentId: 'root',
        path: 'Main',
        showLevel: '2',
        sort: '0',
        title: '系统设置',
        url: '',
        uuid: '27b09153a81b45ce95556d38ef7176f3',
        children: [
          {
            description: '系统设置 - 用户管理',
            icon: 'md-person-add',
            id: '401',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '用户管理',
            url: 'https://ant.design/index-cn',
            uuid: 'cda719d28b1c46f0972f58af04460dd6',
            children: []
          },
          {
            description: '系统设置 - 用户分组',
            icon: 'md-contacts',
            id: '402',
            isOutSide: '0',
            name: 'plugins',
            parentId: 'root',
            path: 'Main',
            showLevel: '2',
            sort: '0',
            title: '用户分组',
            url: 'https://ant.design/index-cn',
            uuid: '002b351ef3b644cf97d8e660a563018a',
            children: []
          }
        ]
      }
    ]
    iframeRoutes = []
    iframeNames = []
    this.menuTree = this.filterMenu(demo)
    console.log(this.menuTree)
    this.$store.commit('setIframeRoutes', iframeRoutes)
    this.$store.commit('setIframeNames', iframeNames)
    this.$store.commit('setApiNav', this.menuTree)

    // 初始化 完成侧栏生成再赋值
    if (sessionStorage.getItem('currentTabs')) {
      let currentTabs = sessionStorage.getItem('currentTabs')
      this.$store.commit('setCurrentTabs', currentTabs)
    } else {
      if (sessionStorage.getItem('tagNaveList')) {
        let tagList = JSON.parse(sessionStorage.getItem('tagNaveList'))
        if (tagList.length !== 0) {
          this.$store.commit('setCurrentTabs', tagList[0].name)
        }
      }
    }
    if (sessionStorage.getItem('tagNaveList')) {
      let tagList = JSON.parse(sessionStorage.getItem('tagNaveList'))
      if (tagList.length === 0) {
        this.$store.commit('setCurrentTabs', '')
      } else {
        this.setTagNavList(tagList)
        let currentTabs = sessionStorage.getItem('currentTabs')
        // currentTabs有无决定刷新显示第一个tab内容
        if (currentTabs) {
          this.$store.commit('setCurrentTabs', currentTabs)
          let index = iframeNames.indexOf(currentTabs)
          this.$set(iframeRoutes[index], 'ifRender', true)
          this.$store.commit('setIframeRoutes', iframeRoutes)
        } else {
          this.$store.commit('setCurrentTabs', tagList[0].name)
          let index = iframeNames.indexOf(tagList[0].name)
          this.$set(iframeRoutes[index], 'ifRender', true)
          this.$store.commit('setIframeRoutes', iframeRoutes)
        }
      }
    } else {
      this.$store.commit('setCurrentTabs', '')
    }
    // return false

    // this.menuTree = []

    // // 获取用户信息
    // this.getUserJAEInfo()

    // // 获取菜单信息
    // let userInfoJson = sessionStorage.getItem('userInfo')
    // let userInfoObj = JSON.parse(userInfoJson)
    // let params = {
    //   // data: '16',
    //   // cmd: 'getallmenujson',
    //   // token: '12345'
    //   // projectId: '78b36ea522194dee9911b01ff631d361'
    //   projectId: '78fc094f33304d86a8ae5c35f1f99e77',
    //   jaeId: userInfoObj.mail,
    //   jaeToken: window.sessionStorage.getItem('tokenJAE')
    // }
    // await systemMenuV2(params).then(res => {
    //   if (res.data.status === 200) {
    //     let arr = [...res.data.data.list]
    //     iframeRoutes = []
    //     iframeNames = []
    //     // let arr = []
    //     this.menuTree = this.filterMenu(arr)
    //     this.$store.commit('setIframeRoutes', iframeRoutes)
    //     this.$store.commit('setIframeNames', iframeNames)
    //     this.$store.commit('setApiNav', this.menuTree)

    //     // 初始化 完成侧栏生成再赋值
    //     // if (sessionStorage.getItem('currentTabs')) {
    //     //   let currentTabs = sessionStorage.getItem('currentTabs')
    //     //   this.$store.commit('setCurrentTabs', currentTabs)
    //     // } else {
    //     //   if (sessionStorage.getItem('tagNaveList')) {
    //     //     let tagList = JSON.parse(sessionStorage.getItem('tagNaveList'))
    //     //     if (tagList.length !== 0) {
    //     //       this.$store.commit('setCurrentTabs', tagList[0].name)
    //     //     }
    //     //   }
    //     // }
    //     // if (sessionStorage.getItem('tagNaveList')) {
    //     //   let tagList = JSON.parse(sessionStorage.getItem('tagNaveList'))
    //     //   if (tagList.length === 0) {
    //     //     this.$store.commit('setCurrentTabs', '')
    //     //   } else {
    //     //     this.setTagNavList(tagList)
    //     //     let currentTabs = sessionStorage.getItem('currentTabs')
    //     //     // currentTabs有无决定刷新显示第一个tab内容
    //     //     if (currentTabs) {
    //     //       this.$store.commit('setCurrentTabs', currentTabs)
    //     //       let index = iframeNames.indexOf(currentTabs)
    //     //       this.$set(iframeRoutes[index], 'ifRender', true)
    //     //       this.$store.commit('setIframeRoutes', iframeRoutes)
    //     //     } else {
    //     //       this.$store.commit('setCurrentTabs', tagList[0].name)
    //     //       let index = iframeNames.indexOf(tagList[0].name)
    //     //       this.$set(iframeRoutes[index], 'ifRender', true)
    //     //       this.$store.commit('setIframeRoutes', iframeRoutes)
    //     //     }
    //     //   }
    //     // } else {
    //     //   this.$store.commit('setCurrentTabs', '')
    //     // }
    //     // 优化TODO
    //     if (sessionStorage.getItem('tagNaveList')) {
    //       let tagList = JSON.parse(sessionStorage.getItem('tagNaveList'))
    //       if (tagList.length < 2) {
    //         let index = iframeNames.indexOf(this.$store.state.app.homeName)
    //         this.setTagNavList([{
    //           name: this.$store.state.app.homeName,
    //           meta: iframeRoutes[index].meta
    //         }])
    //         this.$set(iframeRoutes[index], 'ifRender', true)
    //         this.$store.commit('setIframeRoutes', iframeRoutes)
    //         this.$nextTick(() => {
    //           this.$store.commit('setCurrentTabs', this.$store.state.app.homeName)
    //         })
    //       } else {
    //         this.setTagNavList(tagList)
    //         let currentTabs = sessionStorage.getItem('currentTabs')
    //         if (currentTabs) {
    //           // this.$store.commit('setCurrentTabs', currentTabs)
    //           let index = iframeNames.indexOf(currentTabs)
    //           this.$set(iframeRoutes[index], 'ifRender', true)
    //           this.$store.commit('setIframeRoutes', iframeRoutes)
    //           this.$nextTick(() => {
    //             this.$store.commit('setCurrentTabs', currentTabs)
    //           })
    //         } else {
    //           // this.$store.commit('setCurrentTabs', tagList[0].name)
    //           let index = iframeNames.indexOf(tagList[0].name)
    //           this.$set(iframeRoutes[index], 'ifRender', true)
    //           this.$store.commit('setIframeRoutes', iframeRoutes)
    //           this.$nextTick(() => {
    //             this.$store.commit('setCurrentTabs', tagList[0].name)
    //           })
    //         }
    //       }
    //     } else {
    //       // this.$store.commit('setCurrentTabs', this.$store.state.app.homeName)
    //       sessionStorage.setItem('currentTabs', this.$store.state.app.homeName)
    //       let index = iframeNames.indexOf(this.$store.state.app.homeName)
    //       this.setTagNavList([{
    //         name: this.$store.state.app.homeName,
    //         meta: iframeRoutes[index].meta
    //       }])
    //       this.$set(iframeRoutes[index], 'ifRender', true)
    //       this.$store.commit('setIframeRoutes', iframeRoutes)
    //       this.$nextTick(() => {
    //         this.$store.commit('setCurrentTabs', this.$store.state.app.homeName)
    //       })
    //     }
    //   } else {
    //     this.$Message.error(res.data.data.message)
    //   }
    // }).catch(err => {
    //   console.log('err', err)
    // })
  },
  mounted () {
    if (window.sessionStorage.getItem('collapse')) {
      this.collapsed = JSON.parse(window.sessionStorage.getItem('collapse'))
      this.setCollapse(this.collapsed)
    }

    // 屏蔽F11放大全屏
    document.addEventListener('keydown', (event) => {
      if (event.code === 'F11') {
        event.preventDefault()
        return false
      }
    })

    // 窗口尺寸对侧栏的影响
    this.resizeWindow()
    window.onresize = () => {
      this.resizeWindow()
    }

    // 实时报警数据
    // this.getListData()
    // if (this.env === 'production') {
    //   this.timer = setInterval(() => {
    //     this.getListData()
    //   }, 10000)
    // }

    window.addEventListener('message', (e) => this.getIframeDataTurnTo(e), false)
  },
  destroyed () {
    window.removeEventListener('message', (e) => this.getIframeDataTurnTo(e))
  },
  methods: {
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setHomeRoute',
      'closeTag',
      'setWindowSize',
      'setCollapse'
    ]),
    ...mapActions([
      'handleLogOut',
      'handleLogin',
      'getUnreadMessageCount'
    ]),
    // 接收数据跳转
    getIframeDataTurnTo (e) {
      if (e.data) {
        if (e.data.type === 'event') {
          let obj = e.data.data
          if (obj.name === 'click') {
            // 跳转，固定参数
            this.turnToPage('4405f17577d44532964fe3955acf3352')
            // this.turnToPage('7caea525b3394cc0971dabb1f9cbd5d6')
            let arr = [...this.$store.state.user.iframeRoutes]
            let current = -1
            arr.map((item, index) => {
              if (item.meta.uuid === '4405f17577d44532964fe3955acf3352') {
              // if (item.meta.uuid === '7caea525b3394cc0971dabb1f9cbd5d6') {
                current = index
                return false
              }
            })
            let iframes = document.getElementsByTagName('iframe')
            // 等待加载完成，需要监测DOM节点
            this.$nextTick(() => {
              for (let i = 0; i < iframes.length; i++) {
                if (iframes[i].getAttribute('src') === '/msa/r6-cs/#/dashBoard/realtimeCheck') {
                // if (iframes[i].getAttribute('src') === '/msa/iot-cloud/#/devops-manage/node-manage') {
                  // 第一次加载和不加载，监测加载标志位
                  let timer = setInterval(() => {
                    if (arr[current].meta.finish) {
                      clearInterval(timer)
                      setTimeout(() => {
                        this.sendIframeData(iframes[i], obj.params.cidModel)
                      }, 800)
                    }
                  }, 10)
                }
              }
            })
          }
        }
      }
    },
    sendIframeData (instance, cidModel) {
      instance.contentWindow.postMessage({
        type: 'event',
        data: {
          name: 'click',
          params: {
            cidModel
          }
        }
      }, '*')
    },
    filterMenu (node) {
      return node.map(item => {
        let obj = {}
        // obj.icon = item.ico
        obj.icon = item.icon
        obj.title = item.title
        obj.name = item.uuid
        // obj.path = ''
        obj.iframeComponent = true
        obj.meta = {}
        obj.meta = Object.assign({}, item)
        obj.meta.name = item.uuid
        obj.meta.finish = false
        if (obj.meta.url === '/app/ai-data-view/') obj.meta.hideInMenu = true
        // obj.meta.icon = item.ico
        // obj.meta.icon = item.icon
        delete obj.meta.children
        // 单单用三目obj.children = item.children ? item.children : []只会返回未过滤前的数组
        if (item.children && item.children.length !== 0) {
          // 不只递归运行函数，将返回的obj值赋值到children
          obj.children = [...this.filterMenu(item.children)]
          obj.meta.showAlways = true
        } else {
          obj.children = []
        }
        if (item.url !== '' && this.findHome === 0) {
          this.$store.commit('setHomeName', item.uuid)
          obj.meta.home = true
          this.findHome++
        }
        obj.ifRender = item.uuid === this.currentTabs
        iframeRoutes.push(obj)
        iframeNames.push(obj.name)
        // console.log(obj)
        return obj
      })
    },
    // 获取用户信息
    getUserJAEInfo () {
      let params = { token: sessionStorage['tokenJAE'], cmd: 'getinfo' }
      userJAELogin(params).then(res => {
        if (res.data.error > 0) {
          this.$Message.error(res.data.info)
        } else {
          this.userLv = res.data.data.lv
          this.userName = res.data.data.name
          this.userDetail = {
            userLv: res.data.data.lv,
            userName: res.data.data.name
          }
          this.accountInfo = res.data.data
          sessionStorage.setItem('username', res.data.data.name)
          sessionStorage.setItem('userInfo', JSON.stringify(res.data.data))
        }
      }).catch(err => {
        console.log('err', err)
      })
    },
    turnToPage (route) {
      // console.log(route, 1)
      let newRoute = {}
      if (typeof route === 'string') {
        for (let i = 0; i < iframeRoutes.length; i++) {
          if (iframeRoutes[i].name === route) {
            newRoute = iframeRoutes[i]
            break
          }
        }
        // this.currentTabs = route
        this.$store.commit('setCurrentTabs', route)
      } else {
        newRoute = route
        // this.currentTabs = route.name
        this.$store.commit('setCurrentTabs', route.name)
      }
      const { name, query, params, meta } = newRoute
      this.addTag({
        route: { name, query, params, meta },
        type: 'push'
      })
      sessionStorage.setItem('currentTabs', name)
      // let { name, params, query } = {}
      // if (typeof route === 'string') name = route
      // else {
      //   name = route.name
      //   params = route.params
      //   query = route.query
      // }
      // if (name.indexOf('isTurnByHref_') > -1) {
      //   window.open(name.split('_')[1])
      //   return
      // }
      // this.$router.push({
      //   name,
      //   params,
      //   query
      // })
      let routes = this.$store.state.user.iframeRoutes
      let names = this.$store.state.user.iframeNames
      // console.log(names, name)
      let index = names.indexOf(name)
      if (index !== -1) {
        this.$set(routes[index], 'ifRender', true)
        this.$store.commit('setIframeRoutes', routes)
      }
    },
    handleCollapsedChange (state) {
      this.collapsed = state
      this.setCollapse(state)
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          // 关闭全部
          // this.turnToPage(this.$config.homeName)
          this.turnToPage(this.$store.state.app.homeName)
          // this.$store.commit('setCurrentTabs', '')
          // this.$store.commit('setCurrentTabs', this.$store.state.app.homeName)
          let routes = this.$store.state.user.iframeRoutes
          routes.map(item => {
            // item.ifRender = false
            item.ifRender = item.name === this.$store.state.app.homeName
          })
          this.$store.commit('setIframeRoutes', routes)
        } else {
          // 关闭单个
          // if (routeEqual(this.$route, route)) {
          //   this.closeTag(route)
          // }
          let routes = this.$store.state.user.iframeRoutes
          let names = this.$store.state.user.iframeNames
          let index = names.indexOf(route.name)
          let num = 0
          let tagNavList = this.$store.state.app.tagNavList
          let currentTab = ''
          let len = tagNavList.length
          tagNavList.map((item, i) => {
            if (item.name === route.name) {
              num = i
            }
          })
          // console.log(index, num)
          if (route.name === this.$store.state.user.currentTabs) {
            if (num === len - 1) {
              if (tagNavList && tagNavList.length > 1) {
                currentTab = tagNavList[tagNavList.length - 2].name
                this.$store.commit('setCurrentTabs', currentTab)
                // 应对刷新问题
                let target = names.indexOf(currentTab)
                this.$set(routes[target], 'ifRender', true)
              } else {
                currentTab = ''
                this.$store.commit('setCurrentTabs', '')
              }
            } else if (num === 0) {
              if (tagNavList.length === 1) {
                this.$store.commit('setCurrentTabs', '')
              } else {
                currentTab = tagNavList[1].name
                this.$store.commit('setCurrentTabs', currentTab)
                // 应对刷新问题
                let target = names.indexOf(currentTab)
                this.$set(routes[target], 'ifRender', true)
              }
            } else {
              currentTab = tagNavList[num - 1].name
              this.$store.commit('setCurrentTabs', currentTab)
              // 应对刷新问题
              let target = names.indexOf(currentTab)
              this.$set(routes[target], 'ifRender', true)
            }
          }
          this.$set(routes[index], 'ifRender', false)
          this.$store.commit('setIframeRoutes', routes)
          // this.$store.commit('setIframeNames', names)
          sessionStorage.setItem('currentTabs', currentTab)
        }
      } else {
        // 关闭其它
        let routes = this.$store.state.user.iframeRoutes
        routes.map(item => {
          // if (item.name !== this.$store.state.user.currentTabs) item.ifRender = false
          if (item.name !== this.$store.state.user.currentTabs && item.name !== this.$store.state.app.homeName) item.ifRender = false
        })
        this.$store.commit('setIframeRoutes', routes)
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      this.turnToPage(item)
    },
    // 咨询是否退出系统
    whetherLogout () {
      this.logoutModal = true
    },
    // 退出系统
    logout () {
      this.logoutLoading = true
      // this.setTagNavList([])
      // window.sessionStorage.removeItem('userLogin')
      // window.location.replace('http://10.1.80.84:8503/app/login/')
      // window.open('http://10.1.80.84:8503/app/login/', '_self')
      this.handleLogOut().then(() => {
        this.setTagNavList([])
        this.$store.commit('setCurrentTabs', '')
        window.sessionStorage.removeItem('currentTabs')
        window.sessionStorage.removeItem('tagNaveList')
        // window.sessionStorage.removeItem('tokenJAE')
        // window.sessionStorage.removeItem('accessToken')
        window.sessionStorage.removeItem('userLogin')
        window.sessionStorage.removeItem('username')
        window.sessionStorage.removeItem('userInfo')
        // this.$router.push({
        //   path: '/login'
        // })
        // window.location.replace('http://10.1.80.84:8504/app/ai-login/')
        window.sessionStorage.removeItem('tokenJAE')
        window.sessionStorage.removeItem('msa_token')
        window.location.replace('/app/iot-login/')
      })
    },
    resizeWindow () {
      this.setWindowSize({
        width: document.body.offsetWidth,
        height: document.body.offsetHeight
      })
      // this.collapsed = document.body.offsetWidth < 1100
    },
    // 打开个人信息弹窗
    showMyself () {
      this.showMyselfModal = true
      // this.$router.push({
      //   path: '/self-centre/self-settings'
      // })
    },
    // ws实时
    getRealtimeDataWS () {
      if (typeof (WebSocket) === 'undefined') {
        this.$Message.error('您的浏览器不支持websocket！')
      } else {
        // 实例化websocket
        this.wss = new WebSocket(config.baseUrl.wsServer)
        // 监听websocket连接
        this.wss.onopen = this.open
        // 监听websocket错误信息
        this.wss.onerror = this.error
        // 监听websocket消息
        this.wss.onmessage = this.getMessage
      }
    },
    open () {
      console.log('websocket连接成功！')
    },
    error () {
      console.log('websocket连接错误！')
    },
    getMessage (msg) {
      console.log(msg.data)
      if (msg.data) {
        this.warnCounts++
      }
    },
    send () {
      this.wss.send(params)
    },
    close () {
      console.log('websocket已关闭！')
    },
    // 接口实时
    async getListData () {
      let params = {
        checked: 0,
        currentPage: 1,
        pageSize: 10
      }
      await iotsysWarnList(params).then(res => {
        if (res.data.code > 0) {
          this.$message({ message: res.data.info, type: 'danger' })
        } else {
          this.warnCounts = res.data.page.totalSize
        }
      }).catch(err => {
        this.$message({ message: err.data.info, type: 'danger' })
        console.log(err)
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~_c/animation/ani.styl'

.main
  & >>> .ivu-layout-sider
    background #2f4050
    // background #12293e
  .sider-menu
    overflow hidden
    & >>> .ivu-menu-dark
      // background #2f4050
      // background #0e1e2d
      // background rgb(22, 66, 166)
      background transparent
    .sider-user-info
      box-sizing border-box
      text-align left
      padding 40px 30px
      padding-bottom 10px
      p
        margin 0
      .user-avatar
        border-radius 50%
        cursor pointer
      .user-level
        color #DFE4ED
        font-size 14px
        padding 5px 5px 5px 0px
      .user-name
        color #ccc
    .sider-user-info-xa
      padding 0px 0px
      // padding-bottom 50px
      & > div
        height 150px !important
      img
        margin-left -10px
        // padding 30px 50px
        // padding-bottom 10px
        width 100%
        // margin-bottom 10px
      p
        // font-weight normal !important
        font-size 17px !important
    .sider-user-info-short
      text-align left
      padding 20px 10px
      .user-avatar
        width 32px
        height 32px
    & >>> .ivu-menu-vertical
      overflow hidden
      .ivu-menu-item, .ivu-menu-submenu-title
        white-space nowrap
  .header-con
    & >>> .header-bar
      .custom-content-con
        padding-right 6px
    .jae-sys-welcome
      font-size 14px
      color #888
    .sys-logout
      button
        font-size 14px
        color #888
        padding 15px 0px
        &:hover
          color #57a3f3
        &:focus
          box-shadow unset
  .footer-con
    box-sizing border-box
    line-height 30px
    padding 0px 20px
    box-shadow inset 1px 1px 2px rgba(0, 0, 0, .2)
    background white
    .footer-left
      float left
      font-size 12px
      color #676a6c
    .footer-right
      float right
      font-size 12px
      color #676a6c
.logout-modal
  & >>> .ivu-modal
    top 200px
.show-themes
  // width 180px
  text-align center
  img
    width 100%
.page-settings-drawer
  .ivu-form-item
    margin-bottom 0px

.special-tooltip-self
  & >>> .ivu-tooltip-popper
    z-index 100
    position fixed !important
</style>
